<?php

/**
 * PartyController
 *
 * @author nagata
 * @version
 */

require_once 'Zend/Controller/Action.php';
require_once 'Zend/Validate/EmailAddress.php';
require_once 'Zend/Mail.php';
require_once 'Zend/Auth.php';

require_once 'Okute/Util/Data.php';
require_once 'Okute/Exception.php';

require_once APPLICATION_PATH . '/models/AccountModel.php';
require_once APPLICATION_PATH . '/models/PartyModel.php';
require_once APPLICATION_PATH . '/models/ResetModel.php';
require_once APPLICATION_PATH . '/models/AclModel.php';

class PartyController extends Zend_Controller_Action
{
    /**
     * セッション管理用変数
     * @var Zend_Session_Namespace
     */
    private $_session;

    /**
     * 共通関数用
     * @var Okute_Util_Data
     */
    private $_util;

    /**
     * アクセスコントロール
     * @var Zend_Acl
     */
    private $_acl;

    /**
     * リダイレクトヘルパー
     * @var Okute_Controller_Action_Helper_Redirector
     */
    private $_redirector;

    /**
     * 初期化処理
     *
     * @return void
     */
    public function init()
    {
        $this->_session = new Zend_Session_Namespace('okute');

        $this->_session->requester = null;
        $this->_session->shelter   = null;

        $this->_util = new Okute_Util_Data($this->view);
        $this->_acl = Zend_Registry::get('acl');
        $this->_redirector = Zend_Registry::get('redirector');
        $this->view->base = $this->getRequest()->getBaseUrl();
    }

    /**
     * index: ログイン処理へ転送
     *
     * @return void
     */
    public function indexAction()
    {
        $this->_redirect('/party/login');
    }

    /**
     * ログイン処理
     *
     * @return void
     */
    public function loginAction()
    {
        $this->_session->party = null;
        $this->_session->role  = null;
        $this->_util->clearSessionData();

        $errors = array();
        $this->view->errors = null;

        $this->view->party_id = null;

        if($this->getRequest()->isPost())
        {
            $partyId = $this->_request->getPost('party_id');
            $password = $this->_request->getPost('password');

            if(! Zend_Validate::is($partyId,'NotEmpty'))
            {
                $errors[] = array('code' => '1000', 'message' => 'アカウントIDを入力してください。');
            }

            if(empty($password))
            {
                $errors[] = array('code' => '1001', 'message' => 'パスワードを入力してください。');
            }

            if(count($errors) == 0)
            {
                // 認証アダプタを作成
                $db = Zend_Db_Table::getDefaultAdapter();
                $authAdapter = new Zend_Auth_Adapter_DbTable($db);

                $authAdapter->setTableName('mst_account');
                $authAdapter->setIdentityColumn('account_id');
                $authAdapter->setCredentialColumn('password');
                $authAdapter->setCredentialTreatment("MD5(?) AND account_type IN ('1','2') AND status = '1'");

                $authAdapter->setIdentity($partyId);
                $authAdapter->setCredential($password);

                $auth = Zend_Auth::getInstance();
                $result = $auth->authenticate($authAdapter);

                // 認証成功
                if($result->isValid())
                {
                    Zend_Session::regenerateId();

                    // 要求者インスタンス作成
                    $partyModel = new PartyModel();

                    // 認証情報を保存
                    $this->_session->party = $partyModel->fetchRow(
                        $partyModel->select()->where('party_id = ?', $partyId)
                    );

                    $accountModel = new AccountModel();
                    $account = $accountModel->fetchRow(
                        $accountModel->select()
                                     ->where("account_type IN ('1','2')")
                                     ->where("status = '1'")
                                     ->where('account_id = ?', trim($partyId))
                    );

                    if($account->account_type == '1')
                    {
                        $this->_session->role = 'supporter';
                    }
                    else
                    {
                        $this->_session->role = 'carrier';
                    }

                    $this->_redirector->redirectWithSession($this->view->base.'/support');
                }
                // 認証失敗
                else
                {
                    $errors[] = array('code' => '1001', 'message' => 'ログインに失敗しました');
                }
            }

            $this->view->party_id = $partyId;

            if(count($errors) > 0)
            {
                $this->view->errors = $errors;
            }
        }
    }

    /**
     * かんたんログイン処理
     *
     * @return void
     */
    public function easyAction()
    {
        $errors = null;

        $uid = $this->_getUniqueId();
        if($uid !== null)
        {
            $accountModel = new AccountModel();
            $account = $accountModel->fetchRow(
                $accountModel->select()
                             ->where("account_type IN ('1','2')")
                             ->where("status = '1'")
                             ->where('uid = ?', $uid)
            );
            if($account !== null)
            {
                // 要求者インスタンス作成
                $partyModel = new PartyModel();

                // 認証情報を保存
                $this->_session->party = $partyModel->fetchRow(
                    $partyModel->select()->where('party_id = ?',trim($account->account_id))
                );

                if($account->account_type == '1')
                {
                    $this->_session->role = 'supporter';
                }
                else
                {
                    $this->_session->role = 'carrier';
                }

                $this->_redirector->redirectWithSession($this->view->base.'/support');
            }
            else
            {
                $errors[] = array('code' => '1001', 'message' => 'ログインに失敗しました');
            }
        }
        else
        {
            $errors[] = array('code' => '1001', 'message' => 'かんたんログイン非対応機種です');
        }
        $this->view->party_id = $partyId;

        if(count($errors) > 0)
        {
            $this->view->errors = $errors;
        }
    }

    /**
     * かんたんログイン登録処理
     *
     * @return void
     */
    public function setuidAction()
    {
        if (!$this->_acl->isAllowed($this->_session->role, AclModel::RES_PARTY_MENU)) {
            throw new Okute_Exception('Access Control Error');
        }

        $errors = null;
        $this->view->errors = null;

        $uid = $this->_getUniqueId();
        if($uid === null)
        {
            $errors[] = array('code' => '1001', 'message' => 'かんたんログイン非対応機種です');
            $this->view->errors = $errors;
            return;
        }

        $partyId = $this->_session->party->party_id;
        if($partyId === null)
        {
            throw new Okute_Exception('Session data "party->party_id" is required');
        }

        $accountModel = new AccountModel();
        $account = $accountModel->fetchRow(
            $accountModel->select()->where('account_id = ?', trim($partyId))
        );
        $account->uid = $uid;
        $account->update_datetime = 'NOW()';
        $account->save();

        $errors[] = array('code' => '0000', 'message' => 'かんたんログイン設定が完了しました');
        $this->view->errors = $errors;
    }

    /**
     * ログアウト処理
     *
     * @return void
     */
    public function logoutAction()
    {
        if (!$this->_acl->isAllowed($this->_session->role, AclModel::RES_PARTY_MENU)) {
            throw new Okute_Exception('Access Control Error');
        }

        $this->_session->party = null;
        $this->_util->clearSessionData();
        $this->_redirect('/party/login');
    }

    /**
     * 新規登録処理
     *
     * @return void
     */
    public function registAction()
    {
        $this->_session->party = null;

        $data = null;

        // セッションデータがある場合は「確認画面の戻るボタン」で遷移
        if($this->_session->userData !== null)
        {
            $data = $this->_session->userData;
        }

        // ポストデータがある場合は「入力エラー」により戻された
        if($this->getRequest()->isPost())
        {
            $data = $this->_postToData($this->getRequest(),$data);
        }

        if($data !== null)
        {
            $this->_session->userData = $data;
            if(!isset($data['party_type']))
            {
                $data['party_type'] = null;
            }
        }
        $arrPartyType = array(
                            1 => '支援団体',
                            2 => '輸送団体'
                        );
        $this->view->assign('party_type',$arrPartyType);
        $this->view->back = null;
        $this->view->data = $data;
    }

    /**
     * 編集処理
     *
     * @return void
     */
    public function editAction()
    {
        if (!$this->_acl->isAllowed($this->_session->role, AclModel::RES_PARTY_MENU)) {
            throw new Okute_Exception('Access Control Error');
        }

        $this->_util->clearSessionData();

        $data = null;

        // セッションデータがない場合は「メニューの編集」から遷移
        if($this->_session->userData === null)
        {
            $partyId = $this->_session->party->party_id;
            if($partyId === null)
            {
                throw new Okute_Exception('Session data "party->party_id" is required');
            }

            $partyModel = new PartyModel();
            $res = $partyModel->fetchRow(
                $partyModel->select()->where('party_id = ?',$partyId)
            );
            $data = $res->toArray();

            $accountModel = new AccountModel();
            $res = $accountModel->fetchRow(
                $accountModel->select()->where('account_id = ?',trim($partyId))
            );
            $data['party_type'] = $res->account_type;
        }
        // セッションデータがある場合は「確認画面の戻るボタン」で遷移
        else
        {
            $data = $this->_session->userData;
        }

        // ポストデータがある場合は「入力エラー」により戻された
        if($this->getRequest()->isPost())
        {
            $data = $this->_postToData($this->getRequest(),$data);
        }

        if($data !== null)
        {
            $this->_session->userData = $data;
            if(!isset($data['party_type']))
            {
                $data['party_type'] = null;
            }
        }

        $arrPartyType = array(
                            1 => '支援団体',
                            2 => '輸送団体'
                        );
        $this->view->assign('party_type',$arrPartyType);
        $this->view->data = $data;
    }

    /**
     * 入力内容確認画面
     *
     * @return void
     */
    public function confirmAction()
    {
        $edit = null;
        $back = null;
        $data = null;
        $this->view->errors = null;

        if($this->_session->party === null)
        {
            $edit = false;
            $back = 'regist';
            $this->view->finish = '登録する';
        }
        else
        {
            $edit = true;
            $back = 'edit';
            $this->view->finish = '変更する';
        }

        $data = $this->_session->userData;
        $data = $this->_postToData($this->getRequest(),$data);

        $errors = $this->_checkInput($data,$edit);
        if(count($errors) > 0)
        {
            $this->view->errors = $errors;
            $this->_forward($back);
        }

        $this->_session->userData = $data;
        $this->_session->confirm = true;

        $data['party_type_display'] = null;
        if(isset($data['party_type']))
        {
            switch($data['party_type'])
            {
                case 1:
                $data['party_type_display'] = "支援団体";
                break;

                case 2:
                $data['party_type_display'] = "輸送団体";
                break;
            }
        }
        $this->view->back = $back;
        $this->view->data = $data;
    }

    /**
     * データベース登録/更新処理
     *
     * @return void
     */
    public function finishAction()
    {
        if ($this->_session->userData === null)
        {
            throw new Okute_Exception('Session data "userData" is required');
        }

        if($this->_session->confirm === null)
        {
            throw new Okute_Exception('Invalid page-transition');
        }
        $this->_session->confirm = null;

        $data = $this->_session->userData;

        $accountModel = new AccountModel();
        $partyModel = new PartyModel();

        $db = Zend_Registry::get('database', null);
        if($db === null)
        {
            throw new Okute_Exception('Invalid registry "database"');
        }

        // 新規登録処理
        if($this->_session->party === null)
        {
            $db->beginTransaction();
            try
            {
                $account = $accountModel->createRow();
                $account->account_id      = $data['party_id'];
                $account->password        = md5($data['password']);
                $account->uid             = null;
                $account->account_type    = $data['party_type'];
                $account->status          = '1';
                $account->create_datetime = 'NOW()';
                $account->update_datetime = 'NOW()';
                $account->save();

                $party = $partyModel->createRow();
                $party->party_id            = $data['party_id'];
                $party->party_name          = $data['party_name'];
                $party->representative_tel  = $data['representative_tel'];
                $party->fax                 = $data['fax'];
                $party->url                 = $data['url'];
                $party->representative_name = $data['representative_name'];
                $party->charge_name         = $data['charge_name'];
                $party->department          = $data['department'];
                $party->charge_tel          = $data['charge_tel'];
                $party->charge_mail_address = $data['charge_mail_address'];
                $party->create_datetime = 'NOW()';
                $party->update_datetime = 'NOW()';
                $party->save();

                $db->commit();
                $this->_util->clearSessionData();
            }
            catch (Exception $e)
            {
                $db->rollBack();
                throw $e;
            }
            $this->_redirect('/party/login');
        }
        // 更新処理
        else
        {
            $partyId = $this->_session->party->party_id;
            if($partyId === null)
            {
                throw new Okute_Exception('Session data "party->party_id" is required');
            }

            $db->beginTransaction();
            try
            {
                if((!empty($data['password']))||(!empty($data['party_type'])))
                {
                    $account = $accountModel->fetchRow(
                        $accountModel->select()->where('account_id = ?', trim($partyId))
                    );
                    if(!empty($data['password']))
                    {
                        $account->password    = md5($data['password']);
                    }
                    $account->account_type    = $data['party_type'];
                    $account->update_datetime = 'NOW()';
                    $account->save();
                }

                $party = $partyModel->fetchRow(
                    $partyModel->select()->where('party_id = ?', $partyId)
                );
                $party->party_name          = $data['party_name'];
                $party->representative_tel  = $data['representative_tel'];
                $party->fax                 = $data['fax'];
                $party->url                 = $data['url'];
                $party->representative_name = $data['representative_name'];
                $party->charge_name         = $data['charge_name'];
                $party->department          = $data['department'];
                $party->charge_tel          = $data['charge_tel'];
                $party->charge_mail_address = $data['charge_mail_address'];
                $party->update_datetime = 'NOW()';
                $party->save();

                $db->commit();
                $this->_util->clearSessionData();
            }
            catch(Exception $e)
            {
                $db->rollBack();
                throw $e;
            }

            $this->_redirector->redirectWithSession($this->view->base.'/support');
        }
    }

    /**
     * パスワード再設定申請処理
     *
     * @return void
     */
    public function requestAction()
    {
        $this->view->errors = null;

        $this->_util->clearSessionData();
        $data = null;

        // POSTデータあり
        if($this->getRequest()->isPost())
        {
            $data = $this->_request->getPost();
            $error = $this->_checkMailAddress($data['mail_address']);
            if($error['code'] !== null)
            {
                $this->view->errors = array($error);
                $this->view->data = $data;
                return;
            }

            $partyModel = new PartyModel();
            $party = $partyModel->fetchRow(
                $partyModel->select()->where('charge_mail_address = ?',$data['mail_address'])
            );
            if($party === null)
            {
                $error = array('code' => '1003', 'message' => 'このメールアドレスの登録はありません');
                $this->view->errors = array($error);
                $this->view->data = $data;
                return;
            }

            $accountModel = new AccountModel();
            $account = $accountModel->fetchRow(
                $accountModel->select()->where('account_id = ?',trim($party->party_id))
            );

            /************************
            /* DBに登録
            /************************/

            // ランダムな文字列を生成
            $resetId = $this->_getRandomString();

            $expire = time()+60*60*6;

            $resetModel = new ResetModel();
            $reset = $resetModel->createRow();
            $reset->reset_id        = $resetId;
            $reset->account_id      = $party->party_id;
            $reset->account_type    = $account->account_type;
            $reset->expire_datetime = date('Y-m-d H:i:s.u',$expire);
            $reset->create_datetime = 'NOW()';
            $reset->save();

            /************************
            /* メール送信
            /************************/

            $fromName        = '0910.jp';
            $fromMailAddress = 'info@0910.jp';
            $toName        = $data['mail_address'];
            $toMailAddress = $data['mail_address'];

            if(isset($_SERVER['HTTPS']))
            {
                $url = 'https://'.$_SERVER['SERVER_NAME'];
                if($_SERVER['SERVER_PORT'] != 443)
                {
                    $url .= ':'.$_SERVER['SERVER_PORT'];
                }
            }
            else
            {
                $url = 'http://'.$_SERVER['SERVER_NAME'];
                if($_SERVER['SERVER_PORT'] != 80)
                {
                    $url .= ':'.$_SERVER['SERVER_PORT'];
                }
            }

            $subjest = '[0910.jp]:パスワード再設定';
            $body  = "パスワードの再設定は、以下のページから行ってください。\n\n";
            $body .= "    ".$url.$this->view->base."/party/reset/rid/".$resetId."\n\n";
            $body .= "なお上記ページは".date('Y/m/d H:i:s')."までご利用が可能です。\n";

            // メール自体の文字コード
            $mailCharset = 'ISO-2022-JP';

            // ソースコードの文字コード
            $srcCharset = 'UTF-8';

            //本文を文字コードにあわせて変換
            $fromName = mb_convert_encoding($fromName,$mailCharset,$srcCharset);
            $toName   = mb_convert_encoding($toName  ,$mailCharset,$srcCharset);
            $subjest  = mb_convert_encoding($subjest ,$mailCharset,$srcCharset);
            $body     = mb_convert_encoding($body    ,$mailCharset,$srcCharset);

            //メールを作成する
            $mail = new Zend_Mail($mailCharset);

            $mail->setFrom($fromMailAddress,$fromName);
            $mail->addTo($toMailAddress, $toName);
            $mail->setSubject($subjest);
            $mail->setBodyText($body);

            //送信実行
            try
            {
                $mail->send();
                $error = array('code' => '0000', 'message' => '以下のメールアドレスに再設定ページの案内を送信しました');
                $this->view->errors = array($error);
            }
            catch(Zend_Exception $e)
            {
                throw $e;
            }
        }
        $this->view->data = $data;
    }

    /**
     * パスワード再設定処理
     *
     * @return void
     */
    public function resetAction()
    {
        $this->view->errors = null;
        $errors = null;

        $this->_util->clearSessionData();
        $data = null;

        $resetId = $this->getRequest()->getParam('rid',null);
        if($resetId === null)
        {
            throw new Okute_Exception('GET parameter "rid" is requred');
        }

        $resetModel = new ResetModel();
        $reset = $resetModel->fetchRow(
            $resetModel->select()->where('reset_id = ?',$resetId)
        );
        if($reset === null)
        {
            $errors[] = array('code' => '1001', 'message' => '無効なリクエストです');
            $this->view->errors = $errors;
            $this->view->data = $data;
            $this->view->rid = '/rid/'.$resetId;
            return;
        }
        else if(strtotime($reset->expire_datetime) < time())
        {
            $errors[] = array('code' => '1001', 'message' => '有効期限切れです');
            $this->view->errors = $errors;
            $this->view->data = $data;
            $this->view->rid = '/rid/'.$resetId;
            return;
        }

        // POSTデータあり
        if($this->getRequest()->isPost())
        {
            $data = $this->_request->getPost();

            $validatePasswd = new Zend_Validate_StringLength(8,32);
            if(!$validatePasswd->isValid($data['new_password']))
            {
                $errors[] = array('code' => '1000', 'message' => '8文字から32文字で新しいパスワードを入力してください。');
            }

            if(count($errors) == 0)
            {
                $accountModel = new AccountModel();
                $account = $accountModel->fetchRow(
                    $accountModel->select()->where('account_id = ?',trim($reset->account_id))
                );
                $account->password        = md5($data['new_password']);
                $account->update_datetime = 'NOW()';
                $account->save();

                $reset = $resetModel->fetchRow(
                    $resetModel->select()->where('reset_id = ?',$resetId)
                );
                $reset->delete();

                $this->_redirect('/party/login');
            }
            else
            {
                $this->view->errors = $errors;
            }
        }
        $this->view->data = $data;
        $this->view->rid = '/rid/'.$resetId;
    }

    /**
     * パスワード変更処理
     *
     * @return void
     */
    public function passwdAction()
    {
        if (!$this->_acl->isAllowed($this->_session->role, AclModel::RES_PARTY_MENU)) {
            throw new Okute_Exception('Access Control Error');
        }

        $this->_util->clearSessionData();

        $errors = array();
        $this->view->errors = null;

        $accountModel = new AccountModel();
        $partyId = $this->_session->party->party_id;

        // POSTデータあり
        if($this->getRequest()->isPost())
        {
            $data = $this->_request->getPost();

            // パスワード（必須）
            $validatePasswd = new Zend_Validate_StringLength(8,32);
            if(!$validatePasswd->isValid($data['old_password']))
            {
                $errors[] = array('code' => '1000', 'message' => '8文字から32文字で現在のパスワードを入力してください。');
            }
            else
            {
                $res = $accountModel->fetchRow(
                    $accountModel->select()
                              ->where('account_id = ?',trim($partyId))
                              ->where('password   = MD5(?)',$data['old_password'])
                );
                if($res === null)
                {
                    $errors[] = array('code' => '1000', 'message' => '現在のパスワードが間違っています。');
                }
            }

            if(!$validatePasswd->isValid($data['new_password']))
            {
                $errors[] = array('code' => '1000', 'message' => '8文字から32文字で新しいパスワードを入力してください。');
            }

            if(count($errors) == 0)
            {
                $account = $accountModel->fetchRow(
                    $accountModel->select()->where('account_id = ?', trim($partyId))
                );
                $account->password        = md5($data['new_password']);
                $account->update_datetime = 'NOW()';
                $account->save();

                $this->_redirector->redirectWithSession($this->view->base.'/support');
            }
            else
            {
                $this->view->errors = $errors;
            }
        }
    }

    private function _postToData($request,$data)
    {
        $columns = array(
            'party_id',
            'party_type',
            'password',
            'party_name',
            'representative_tel',
            'fax',
            'url',
            'representative_name',
            'charge_name',
            'department',
            'charge_tel',
            'charge_mail_address',
        );
        foreach ($columns as $column)
        {
            $val = $request->getPost($column);
            if($val !== null)
            {
                $data[$column] = $this->_util->convertInputEncoding($val);
            }
        }
        return $data;
    }

    /**
     * ユーザ入力のエラーを確認する。エラーが存在した場合には配列にエラーコードとメッセージを含めて返却する。
     * 引数にはRequestModelのデータを入力する。
     *
     * @param Zend_Db_Table_Row $data
     * @return array $errors
     */
    private function _checkInput($data,$edit = false)
    {
        $errors = array();

        if($edit === false)
        {
            // アカウントID   : party_id
            if(! Zend_Validate::is($data['party_id'],'NotEmpty'))
            {
                $errors[] = array('code' => '1000', 'message' => 'アカウントIDを入力してください。');
            }
            else
            {
                $accountModel = new AccountModel();
                $res = $accountModel->fetchRow(
                    $accountModel->select()->where('account_id = ?',trim($data['party_id']))
                );
                if($res !== null)
                {
                    $errors[] = array('code' => '1001', 'message' => 'このアカウントIDは既に使用されています。');
                }
            }
        }

        // 団体種別       : party_type
        if(!isset($data['party_type']) || !Zend_Validate::is($data['party_type'],'NotEmpty'))
        {
            $errors[] = array('code' => '1002', 'message' => '団体種別を選択してください。');
        }

        // 団体名         : party_name
        // 代表電話番号   : representative_tel
        // FAX            : fax
        // URL            : url
        // 代表者氏名     : representative_name
        // 担当者氏名     : charge_name
        // 担当者部署名   : department
        // 担当者電話番号 : charge_tel

        // 担当者メール   : charge_mail_address
        $error = $this->_checkMailAddress($data['charge_mail_address']);
        if( $error !== null)
        {
            $errors[] = $error;
        }

        if(($edit === false)||(!empty($data['password'])))
        {
            // パスワード : password
            $validatePasswd = new Zend_Validate_StringLength(8,32);
            if(!$validatePasswd->isValid($data['password']))
            {
                $errors[] = array('code' => '1000', 'message' => '8文字から32文字でパスワードを入力してください。');
            }
        }

        return $errors;
    }

    private function _checkMailAddress($mail_address)
    {
        $error = null;

        // メールアドレス（必須）
        if(!Zend_Validate::is($mail_address,'EmailAddress'))
        {
            $error = array('code' => '1000', 'message' => '有効なメールアドレスを入力してください。');
        }

        return $error;
    }

    private function _getUniqueId()
    {
        require_once('Net/UserAgent/Mobile.php');

        $uid = null;

        $agent = Net_UserAgent_Mobile::singleton();

        // DoCoMo の場合
        if($agent->isDoCoMo())
        {
            if(method_exists( $agent,"getUID"))
            {
                $uid = $agent->getUID();
            }
            if(empty($uid) && method_exists( $agent,"getSerialNumber"))
            {
                $uid = $agent->getSerialNumber();
            }
        }
        // AU の場合
        else if($agent->isEZweb())
        {
            if(method_exists( $agent,"getUID"))
            {
                $uid = $agent->getUID();
            }
            if(empty($uid) && method_exists( $agent,"getDeviceID"))
            {
                $uid = $agent->getDeviceID();
            }
        }
        // Softbank の場合
        else if($agent->isSoftbank())
        {
            if(method_exists( $agent,"getUID"))
            {
                $uid = $agent->getUID();
            }
            if(empty($uid) && method_exists( $agent,"getSerialNumber"))
            {
                $uid = $agent->getSerialNumber();
            }
        }
        return $uid;
    }

    private function _getRandomString()
    {
        $list = "abcdefghijklmnopqrstuvwxyz_0123456789%ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $rand = '';
        for($i=0;$i<32;$i++)
        {
            $rand .= $list{mt_rand(0,strlen($list)-1)};
        }
        return md5($rand);
    }
}
